import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useSystemStore } from '@/stores/system'
import adminRoutes from './modules/admin'
import publicRoutes from './modules/public'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...publicRoutes,
    adminRoutes,
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/error/NotFound.vue'),
      meta: {
        title: '404',
        hidden: true
      }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const systemStore = useSystemStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  // 如果系统配置未加载，先加载配置
  if (!systemStore.systemConfig.frontendName && !systemStore.systemConfig.backendName) {
    await systemStore.fetchSystemConfig()
  }
  
  // 设置页面标题
  const title = to.meta.title 
    ? `${to.meta.title} - ${systemStore.getSystemName()}`
    : systemStore.getSystemName()
  document.title = title

  // 登录验证和重定向逻辑
  if (requiresAuth && !userStore.isLoggedIn) {
    next({
      path: '/admin/login',
      query: { redirect: to.fullPath },
      replace: true
    })
  } else if (to.path === '/admin/login' && userStore.isLoggedIn) {
    next({ path: '/admin/certificates' })
  } else {
    next()
  }
})

export default router
